//
//  CoreImageViewController.m
//  模糊效果
//
//  Created by yq on 2022/6/16.
//

#import "CoreImageViewController.h"

@interface CoreImageViewController ()
@property (nonatomic, strong) UIImageView *iv;
@end

@implementation CoreImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"CoreImage";
    /*
     CoreImage是苹果用来简化图片处理的框架
     */
//    CIImage
//    CIFilter
//    CIContext

//    CIGaussianBlur
    
    UIImage *image = [UIImage imageNamed:@"cat.jpg"];
    //640 × 1024
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 640 * 0.5, 1024 * 0.5)];
    iv.image = image;
    
    [self.view addSubview:iv];
    //ViewDidLoad中设置中心点 无效
//    iv.center = self.view.center;
//    NSLog(@"1%@", NSStringFromCGPoint(self.view.center));
    self.iv = iv;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    NSLog(@"2%@", NSStringFromCGPoint(self.view.center));
//    self.iv.center = self.view.center;
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
//    NSLog(@"3%@", NSStringFromCGPoint(self.view.center));
    self.iv.center = self.view.center;
}

- (void)viewDidAppear:(BOOL)animated {
//    NSLog(@"4%@", NSStringFromCGPoint(self.view.center));
//    self.iv.center = self.view.center;
}
//打印顺序 1234 2就正常了

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UIImage *image = [UIImage imageNamed:@"cat.jpg"];
    //图片输入源
    CIImage *ciImage = [[CIImage alloc] initWithImage:image];
    
    //滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    //滤镜参数及相关信息
    //NSLog(@"%@", [filter attributes]);
    //设置模糊程度
    [filter setValue:@(5) forKey:@"inputRadius"];
    //将图片输入到滤镜中
    [filter setValue:ciImage forKey:kCIInputImageKey];
    //从滤镜中取出处理好的图片
    CIImage *outImage = [filter valueForKey:kCIOutputImageKey];
    //默认CPU渲染
    CIContext *content = [CIContext contextWithOptions:nil];
    
    //获取CGImage句柄
    CGImageRef cgImage = [content createCGImage:outImage fromRect:[outImage extent]];
    
    UIImage *blurImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    
    self.iv.image = blurImage;
}

@end
